import sqlite3
import os

# 数据库路径
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "users.db")

# 创建数据目录
os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)), "data"), exist_ok=True)

# 创建数据库表并添加测试用户（使用明文密码）
def create_test_users_simple():
    # 连接数据库
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    # 创建user表（如果不存在）
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS user (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username VARCHAR(80) UNIQUE NOT NULL,
        password VARCHAR(120) NOT NULL,
        is_admin BOOLEAN NOT NULL DEFAULT 0,
        full_name VARCHAR(100),
        gender VARCHAR(10),
        nickname VARCHAR(80),
        email VARCHAR(120),
        phone VARCHAR(20)
    )
    ''')
    
    # 添加或更新admin用户（使用明文密码）
    cursor.execute("SELECT id FROM user WHERE username = ?", ("admin",))
    admin_exists = cursor.fetchone()
    
    if admin_exists:
        # 更新现有admin用户
        cursor.execute(
            "UPDATE user SET password = ?, is_admin = ?, full_name = ?, nickname = ? WHERE username = ?",
            ("admin", 1, "管理员", "admin", "admin")
        )
    else:
        # 创建新的admin用户
        cursor.execute(
            "INSERT INTO user (username, password, is_admin, full_name, nickname) VALUES (?, ?, ?, ?, ?)",
            ("admin", "admin", 1, "管理员", "admin")
        )
    
    # 添加或更新user1用户（使用明文密码）
    cursor.execute("SELECT id FROM user WHERE username = ?", ("user1",))
    user1_exists = cursor.fetchone()
    
    if user1_exists:
        # 更新现有user1用户
        cursor.execute(
            "UPDATE user SET password = ?, is_admin = ?, full_name = ?, nickname = ? WHERE username = ?",
            ("password1", 0, "普通用户", "user1", "user1")
        )
    else:
        # 创建新的user1用户
        cursor.execute(
            "INSERT INTO user (username, password, is_admin, full_name, nickname) VALUES (?, ?, ?, ?, ?)",
            ("user1", "password1", 0, "普通用户", "user1")
        )
    
    # 提交更改并关闭连接
    conn.commit()
    conn.close()
    
    print("测试用户创建成功！")
    print("注意：此脚本使用明文密码进行测试，仅用于开发环境！")
    print("可用账号：")
    print("- 管理员账号: admin/admin")
    print("- 普通用户账号: user1/password1")

if __name__ == "__main__":
    create_test_users_simple()